# -*- coding: utf-8 -*-

from openerp.osv import osv
from openerp import SUPERUSER_ID
from openerp.osv import fields
from openerp.addons.dftg_weixin.application.application_weixin_contact import WxAppContact
from weixin_sync_operation import WXSyncOperation

class hr_employee(osv.osv):
    _inherit = 'hr.employee'
    _columns = {
        'is_leader': fields.boolean(u'上级(用于企业微信审批)')
    }

    def synchronous_to_weixin(self, cr, uid, ids, context=None):
        contacts_obj = self.pool.get('weixin.contacts')
        for hr_employee in self.browse(cr, uid, ids, context=context):
            if not hr_employee.user_id:
                raise osv.except_osv(u'请为员工创建用户！')
            self.compare_employee_construct(cr, uid, hr_employee.id, context=context)
            contacts_id = contacts_obj.search(cr, uid, [('odoo_user_id', '=', hr_employee.user_id.id)],
                                                        context=context)
            contacts_obj.sync_contacts(cr, uid, contacts_id, context=context)
        return True

    def leave_office(self, cr, uid, ids, context=None):
        contacts_obj = self.pool.get('weixin.contacts')
        for employee in self.browse(cr, SUPERUSER_ID, ids, context=context):
            employee.write({'active': False})
            if employee.user_id:
                employee.user_id.write({'active': False})
                weixin_contacts_id = contacts_obj.search(cr, SUPERUSER_ID,
                                                         [('odoo_user_id', '=', employee.user_id.id)], context=context)
                weixin_contacts_row = contacts_obj.browse(cr, SUPERUSER_ID, weixin_contacts_id, context=context)
                if weixin_contacts_row.sync_status != 'create' or not weixin_contacts_row.sync_status:
                    weixin_contacts_row.write({'sync_status': 'delete'})
                    contacts_obj.sync_contacts(cr, SUPERUSER_ID, weixin_contacts_row.id, context=context)
        return True

    def restoration_office(self, cr, uid, ids, context=None):
        contacts_obj = self.pool.get('weixin.contacts')
        weixin_contact = WxAppContact()
        access_token = weixin_contact.access_token
        for hr_employee in self.browse(cr, uid, ids, context=context):
            hr_employee.write({'active': True})
            if hr_employee.user_id:
                hr_employee.user_id.write({'active': True})
                contacts_ids = contacts_obj.search(cr, uid, [('odoo_user_id', '=',  hr_employee.user_id.id),'|',
                                                             ('active', '=', True),
                                                             ('active', '=', False)],
                                                   context=context)
                contacts_obj.write(cr, uid, contacts_ids, {'active': True, 'is_disabled': False}, context=context)
                for contacts_id in contacts_ids:
                    vals = {'userid': contacts_id, "enable": 1}
                    WXSyncOperation.sync_user_by_operation(access_token, vals, operation='update')
        return True

    def compare_employee_construct(self, cr, uid, active_id, context=None):
        employee_ids = self.search(cr, uid, [('active', '=', True), ('id', '=', active_id)], context=context)
        contacts_obj = self.pool.get('weixin.contacts')
        all_val = {'name': 'name',  'email': 'work_email', 'department': 'department_id', 'isleader': 'is_leader',
                   'partner_id': 'address_home_id', 'mobile': 'mobile_phone', 'odoo_user_id': 'user_id',
                   'telephone': 'work_phone', 'position': 'job_id'}
        field_type = {'name': 'char', 'department_id': 'depart_many2one_many2many', 'address_home_id': 'many2one',
                      'work_email': 'char', 'mobile_phone': 'char', 'user_id': 'many2one', 'is_leader': 'boolean',
                      'job_id': 'many2one_name', 'work_phone': 'char'}
        for employee in self.browse(cr, uid, employee_ids, context=context):
            contacts_id = contacts_obj.search(cr, uid, [('odoo_user_id', '=', employee.user_id.id),
                                                        '|', ('active', '=', True),
                                                        ('active', '=', False)], context=context)
            create_write_val = {key: self.get_field_val_by_type(cr, uid, employee[all_val.get(key)],
                                                                field_type.get(all_val.get(key)), context=context)
                                for key in all_val.keys()}
            if contacts_id:
                contacts_row = contacts_obj.browse(cr, uid, contacts_id, context=context)
                write_val = {}
                for key in all_val.keys():
                    compare_result = self.compare_val(create_write_val.get(key), contacts_row[key], field_type.get(all_val.get(key)))
                    if not compare_result:
                        write_val.update({key: create_write_val.get(key)})
                if write_val:
                    contacts_obj.write(cr, uid, contacts_id, write_val, context=context)
            else:
                contacts_obj.create(cr, uid, create_write_val, context=context)
        return True

    def delete_contacts_department(self, cr, uid, user_id, department_id, context=None):
        contacts_obj = self.pool.get('weixin.contacts')
        department_obj = self.pool.get('wechat.department')
        contact_id = contacts_obj.search(cr, uid, [('odoo_user_id', '=', user_id)], context=context)
        department_ids = department_obj.search(cr, uid, [('system_department_id', '=', department_id)], context=context)
        if department_ids:
            contacts_obj.write(cr, uid, contact_id, {'department': [(3, department_ids[0])]}, context=context)

    def write(self, cr, uid, ids, vals, context=None):
        for employee_row in self.browse(cr, uid, ids, context=context):
            if employee_row.user_id and vals.get('department_id'):
                self.delete_contacts_department(cr, uid, employee_row.user_id.id,
                                                employee_row.department_id.id, context=context)
        return_val = super(hr_employee, self).write(cr, uid, ids, vals, context=context)
        for employee_row in self.browse(cr, uid, ids, context=context):
            self.compare_employee_construct(cr, uid, employee_row.id, context=context)
        if vals.get('is_leader'):
            self.add_department_manage(cr, uid, ids, vals, context=context)
        return return_val

    def create(self, cr, uid, vals, context=None):
        employee_id = super(hr_employee, self).create(cr, uid, vals, context=context)
        if vals.get('user_id'):
            self.compare_employee_construct(cr, uid, employee_id, context=context)
        if vals.get('is_leader'):
            self.add_department_manage(cr, uid, [employee_id], vals, context=context)
        return employee_id

    def add_department_manage(self, cr, uid, ids, vals, context=None):
        """ # #IJNLO 人力资源－员工form页面有3个地方可以设置上级（部门经理），需要进行简化"""
        if not ids and not vals.get('department_id'):
            raise osv.except_osv(u'错误', u'请输入用户部门！')
        for hr_employee_row in self.browse(cr, uid, ids, context=context):
            if vals.get('department_id'):
                department = self.pool.get('hr.department').browse(cr, uid, vals.get('department_id'), context=context)
            else:
                department = hr_employee_row.department_id
            department.write({'manager_id': hr_employee_row.id})
            employee_ids = self.search(cr, uid, [('department_id', '=', department.id)], context=context)
            not_leader_employee_ids = list(set(employee_ids).difference(set([hr_employee_row.id])))
            if hr_employee_row.parent_id and hr_employee_row.parent_id.department_id\
                and hr_employee_row.parent_id.department_id and hr_employee_row.parent_id.department_id.id == department.id:
                hr_employee_row.write({'parent_id': False})
            else:
                self.write(cr, uid, not_leader_employee_ids, {'parent_id': hr_employee_row.id}, context=context)
            if not_leader_employee_ids:
                self.write(cr, uid, not_leader_employee_ids, {'is_leader': False}, context=context)

    def compare_val(self, val_new, val_old, field_type):
        if field_type == 'char':
            return_val = val_new == val_old
        elif field_type == 'many2one':
            return_val = val_new == val_old.id
        elif field_type == 'boolean':
            return_val = val_new == val_old
        elif field_type == 'many2one_name':
            return_val = (val_new or '') == (val_old or '')
        elif field_type == 'depart_many2one_many2many':
            return_val = (val_new and val_new[0][1]) in [val.id for val in val_old]
        else:
            return_val = val_new == val_old
        return return_val

    def get_field_val_by_type(self, cr, uid, val, field_type, context=None):
        department_obj = self.pool.get('wechat.department')
        if field_type == 'char':
            return_val = val
        elif field_type == 'many2one':
            return_val = val.id
        elif field_type == 'many2one_name':
            return_val = val.name or ''
        elif field_type == 'depart_many2one_many2many':
            department_id = department_obj.search(cr, uid, [('system_department_id', '=', val.id)], context=context)
            if department_id:
                return_val = [(4, department_id[0])]
            else:
                return_val = False
        else:
            return_val = val
        return return_val

# class hr_expense_expense(osv.osv):
#     _inherit = 'hr.expense.expense'
#
#     # def expense_confirm(self, cr, uid, ids, context=None):
#     #     for expense in self.browse(cr, uid, ids, context=context):
#     #         if expense.employee_id.parent_id.user_id != uid:
#     #             raise osv.except_osv(u'只能审批，自己部门的员工！')
#     #     return_val = super(hr_expense_expense, self).expense_confirm(cr, uid, ids, context=context)
#     #     return return_val
#
#     def expense_accept(self, cr, uid, ids, context=None):
#         for expense in self.browse(cr, uid, ids, context=context):
#             if expense.employee_id.parent_id.user_id.id != uid:
#                 raise osv.except_osv(u'错误', u'只能审批，自己部门的员工！')
#         return_val = super(hr_expense_expense, self).expense_accept(cr, uid, ids, context=context)
#         return return_val
#
#     def expense_canceled(self, cr, uid, ids, context=None):
#         for expense in self.browse(cr, uid, ids, context=context):
#             if expense.employee_id.parent_id.user_id.id != uid:
#                 raise osv.except_osv(u'错误', u'只能审批，自己部门的员工！')
#         return_val = super(hr_expense_expense, self).expense_canceled(cr, uid, ids, context=context)
#         return return_val
#
#     # def expense_accept(self, cr, uid, ids, context=None):
#     #     return self.write(cr, uid, ids,
#     #                       {'state': 'accepted', 'date_valid': time.strftime('%Y-%m-%d'), 'user_valid': uid},
#     #                       context=context)
#     #
#     # def expense_canceled(self, cr, uid, ids, context=None):
#     #     return self.write(cr, uid, ids, {'state': 'cancelled'}, context=context)
